<template>
  <div>
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>分类参数</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <!-- 警示提示框 -->
      <el-alert title="注意：只允许为第三级分类设置相关参数" type="warning" :closable='false' show-icon center>
      </el-alert>
      <el-row class="cat_opt">
        <el-col>
          <span>商品分类：</span>
          <el-cascader clearable v-model="selectKeys" :options="cateList" :props="cascaderProps" @change="handleChange">
          </el-cascader>
        </el-col>
      </el-row>
      <!-- tabs区域 -->
      <el-tabs v-model="activeName" @tab-click="handleClick">
        <el-tab-pane label="动态参数" name="many">
          <!-- 动态列表 -->
          <el-button type="primary" class="bt_dynamics" :disabled='isBtnDisabled' @click="addDialogVisibleText=true">
            添加动态参数</el-button>
          <!-- 动态参数表格 -->
          <el-table :data="manyTabData" border stripe>
            <!-- 展开行 -->
            <el-table-column type="expand" label="展开">
              <template v-slot='{row}'>
                <el-tag @close="handRemove(row,index)" v-for="(item,index) in row.attr_vals" :key="index" closable="">
                  {{item}}
                </el-tag>
                <!-- 添加框 -->
                <el-input class="input-new-tag" v-if="row.inputVisible" v-model="row.inputValue" ref="saveTagInput"
                  size="small" @keyup.enter.native="handleInputConfirm(row)" @blur="handleInputConfirm(row)">
                </el-input>
                <el-button v-else class="button-new-tag" size="small" @click="showInput(row)">+ New Tag</el-button>
              </template>
            </el-table-column>
            <el-table-column type="index" label="#">
            </el-table-column>
            <el-table-column prop="attr_name" label="参数名称">
            </el-table-column>
            <el-table-column label="操作">
              <template slot-scope='scope'>
                <el-button type="primary" icon='el-icon-edit' @click="showEditDialog(scope.row.attr_id)">编辑</el-button>
                <el-button type="danger" icon='el-icon-delete' @click='remove'></el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="静态参数" name="only">
          <!-- 静态列表 -->
          <el-button type="primary" class="btn_static" :disabled='isBtnDisabled' @click="addDialogVisibleText=true">
            添加静态参数
          </el-button>
          <el-table :data="onlyTabData">
            <el-table-column type="expand" label="展开">
            </el-table-column>
            <el-table-column type="index" label="#">
            </el-table-column>
            <el-table-column prop="attr_name" label="参数名称">
            </el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button type="primary" icon='el-icon-edit' @click="showEditDialog(scope.row.attr_id)">编辑</el-button>
                <el-button type="danger" icon='el-icon-delete' @click='remove'></el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <!-- 添加参数对话框-->
    <el-dialog :title="titleText" :visible.sync="addDialogVisibleText" width="50%" @close="dialogBeforeClose">
      <!-- 添加参数的对话框 -->
      <el-form ref="addFormRef" label-width="100px" :model="addForm" :rules="addFormRules">
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="addForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="addDialogVisibleText = false">取 消</el-button>
        <el-button type="primary" @click="addCate">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 修改参数对话框 -->
    <el-dialog :title="'修改'+titleText" :visible.sync="editDialogVisibleText" width="50%" @close="dialogBeforeClose">
      <!-- 修改参数的对话框 -->
      <el-form ref="addFormRef" label-width="100px" :model="editForm" :rules="addFormRules">
        <erl-form-item :label='titleText' prop='attr_name'>
          <el-input v-model="editForm.attr_name"></el-input>
        </erl-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="editDialogVisibleText = false">取 消</el-button>
        <el-button type="primary" @click="saveCateEdit">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data () {
    return {
      inputVisible: false,
      inputValue: '',
      editForm: {},
      editDialogVisibleText: false,
      // 添加参数的表单数据对象
      addForm: {
        attr_name: ''
      },
      // 添加参数的表单数据对象规则
      addFormRules: {
        attr_name: [
          { required: true, message: '请输入分类名称', trigger: 'blur' }
        ]
      },
      addDialogVisibleText: false,
      activeName: 'many',
      manyTabData: [],
      onlyTabData: [],
      // props配置项
      cascaderProps: {
        expandTrigger: 'hover',
        label: 'cat_name',
        value: 'cat_id',
        children: 'children'
      },
      selectKeys: [],
      cateList: []
    }
  },
  methods: {
    async saveTags (row) {
      const { data: res } = await this.$http.put(`categoties${this.cateId}attributes/${row.attr_id}`, { attr_name: row.attr_name, attr_sel: this.activeName, attr_vals: row.attr_vals.join(' ') })
      if (res.meta.status !== 200) return this.$message.error('shibai')
      row.inputValue = ''
      row.inputVisible = false
    },
    handRemove (row, index) {
      row.attr_vals.splice(index, 1)
      this.saveTags(row)
    },
    async handleInputConfirm (row) {
      if (row.inputValue.trim().length === 0) {
        row.inputValue = ''
        row.inputVisible = false
        return
      }
      console.log('fasong axios')
      row.attr_vals.push(row.inputValue)
      const { data: res } = await this.$http.put(`categoties${this.cateId}attributes/${row.attr_id}`, { attr_name: row.attr_name, attr_sel: this.activeName, attr_vals: row.attr_vals.join(' ') })
      if (res.meta.status !== 200) return this.$message.error('shibai')
      row.inputValue = ''
      row.inputVisible = false
    },
    showInput (row) {
      row.inputVisible = true
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
    remove (id) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const { data: res } = await this.$http.delete(`categories${this.cateId}/attributes/${id}`)
        if (res.meta.status !== 200) return this.$message.error('添加失败1212')
        this.getParamsCateList()
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },

    saveCateEdit () {
      this.$refs.editFormRef.resetFields(async bool => {
        const { data: res } = await this.$http.put(`categories/${this.cateId}/attributes/${this.editForm.attr_id}`,
          { attr_name: this.editForm.attr_name, attr_sel: this.activeName })
        if (res.meta.status !== 200) return this.$message.error('添加失败')
        this.editDialogVisibleText = false
        this.getParamsCateList()
      })
    },
    async showEditDialog (id) {
      const { data: res } = await this.$http.get(`categories${this.cateId}attributes/${id}`, { params: { attr_sel: this.activeName } })
      if (res.meta.status !== 200) return this.$message.error('获取参数信息失败1223')
      this.editForm = res.data
      this.editDialogVisibleText = false
    },
    // 点击按钮 添加参数/
    addCate () {
      this.$refs.addFormRef.resetFields(async bool => {
        if (!bool) return
        const { data: res } = await this.$http.psot(`categories/${this.cateId}/attributes`, { attr_sel: this.activeName, attr_name: this.addForm.attr_name })
        if (res.meta.status !== 201) return this.$message.error('添加失败参数')
        this.$message.success('添加成功')
        this.addDialogVisibleText = false
        this.getParamsData()
      })
    },
    // 监听添加对话框的关闭事件 对话框重置
    dialogBeforeClose () {
      this.$refs.addFormRef.resetFields()
    },
    async getParamsCateList () {
      // this.isloading = true
      const { data: res } = await this.$http.get('categories')
      if (res.meta.status !== 200) return this.$message.error('获取失败1')
      // this.$message.success('获取成功')
      this.cateList = res.data
      // this.total = res.data.total
      // this.isloading = false
      console.log(this.cateList)
    },
    handleClick () {
      this.getParamsData()
    },
    // 当联级菜单发生改变时  发起请求回事promise函数
    handleChange () {
      this.getParamsData()
      // 判断是否选中三级分类  如果不是 就清空联级内的内容
      // 因为我们只允许选择三级联级内容
      if (this.selectKeys.length !== 3) {
        this.selectKeys = this.manyTabData = this.onlyTabData = []
      }
    },
    async getParamsData () {
      // 证明选择的是三级联级内容 console.log(this.selectKeys)
      const { data: res } = await this.$http.get(`categories/${this.cateId}/attributes`,
        { params: { sel: this.activeName } })
      console.log(res)
      // 赋值钱江数据二次加工
      if (res.meta.status !== 200) {
        return this.$message.error('获取参数列表失败')
      }
      console.log(res.data)
      res.data.forEach(item => {
        // 做好判断在赋值
        if (item.attr_vals === '') {
          item.attr_vals = []
        } else {
          item.attr_vals = item.attr_vals.split(' ')
        }
        item.inputVisible = false
        item.inputValue = ''
      })
      if (this.activeName === 'only') {
        this.onlyTabData = res.data
      } else {
        this.manyTabData = res.data
      }
    }
  },
  // 计算属性
  computed: {
    // 通过计算属性 计算 选中数据的长度 来控制按钮的状态
    isBtnDisabled () {
      // 如果按钮需要被禁用 就返回ture
      if (this.selectKeys.length !== 3) {
        return true
      }
      return false
    },
    cateId () {
      if (this.selectKeys.length === 3) {
        return this.selectKeys[2]
      }
      return null
    },
    titleText () {
      return this.activeName === 'only' ? '添加静态属性' : '添加动态属性'
    }
  },
  watch: {},
  filters: {},
  components: {},
  created () {
    this.getParamsCateList()
    // ----------------
  },
  mounted () { }
}
</script>

<style scoped lang='less'>
.cat_opt {
  margin: 15px 0;
}
.bt_dynamics {
  margin-bottom: 20px;
}
.btn_static {
  margin-bottom: 20px;
}
</style>
